<template>
  <page-wrap :show-top="showTop" hide-tab back title="DISC性格测评">
    <div class="question">
      <div class="top"></div>
      <div class="question-wrap">
        <p class="title">
          当前进度：
          <span class="num">{{ current }}/{{ total }}</span>
        </p>
        <p class="tips">请选择最符合你的一个</p>
        <ul
          :class="['question-list', picking ? ' disabled' : '']"
          v-if="question.length > 0"
        >
          <transition-group :name="transitionName" tag="ul">
            <li
              :class="[
                'question-item',
                idx === item.title_options_id ? ' active' : '',
                picking ? ' pick' : '',
              ]"
              v-for="(item, index) in question[current - 1].options"
              :key="item.title_options_id"
              @click="throttlePick(item, index)"
            >
              <p class="name">{{ formatTitle(item.options) }}</p>
              <p class="explan">{{ formatDesc(item.options) }}</p>
            </li>
          </transition-group>
        </ul>
        <div class="btn-bar">
          <button
            :class="['btn prev', current > 1 ? '' : ' disabled']"
            @click="handleChange('prev')"
          >
            上一题
          </button>
          <button
            :class="['btn next', current < question.length ? '' : ' disabled']"
            @click="handleChange('next')"
          >
            下一题
          </button>
        </div>
        <button
          :class="[
            'submit-btn',
            canSubmit ? ' success' : ' disabled',
            submitting ? ' disabled' : '',
          ]"
          @click="handleSubmit"
        >
          <span class="loading" v-show="submitting">
            <img src="../assets/images/loading.png" />
          </span>
          {{ submitting ? "提交中..." : "提交" }}
        </button>
        <p class="info">请凭你的第一感觉快速作答，无需针对各种情况反复揣摩。</p>
      </div>
      <button
        class="download-app back-btn"
        v-if="from == 'miniprogram' || from == 'careerPathResult'"
        @click="backMini"
      >
        返回小程序
      </button>
    </div>
  </page-wrap>
</template>

<script>
import { getAnswerList, addAnswer } from "@/api/index";
import { throttle } from "@/utils/event";
export default {
  components: {},
  data() {
    return {
      current: 1,
      canSubmit: false,
      idx: null,
      question: [],
      showTip: false,
      loading: false,
      transitionName: "",
      picking: false,
      submitting: false,
      throttlePick: "",
      currentPersonId: "",
      currentId: "",
      currentPaperId: "",
      from: "",
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
    };
  },
  created() {
    let name = this.$route.query.iname;
    let phone = this.$route.query.phone;
    this.from = this.$route.query.from;

    if (personId) {
      let params = {
        iname: name,
        phone: phone,
      };
      login(params)
        .then((res) => {
          console.log("login", res.code);
          if (+res.code === 200) {
            sessionStorage.setItem("userInfo", JSON.stringify(res.data));
            sessionStorage.setItem("userId", res.data.user_id);
            sessionStorage.setItem("userName", params.iname);
            this.getList();
            if (this.answerList && this.answerList.length > 0) {
              this.idx = this.answerList[this.current - 1].pick;
            }
            this.currentId = res.data.user_id;
            this.currentPaperId = res.data.test_paper_id;
          } else {
            this.showTips(res.status_desc);
          }
        })
        .catch((err) => {
          this.submitting = false;
          this.showTips(err);
        });
    } else {
      if (this.test_paper_id) {
        this.getList();
        if (this.answerList && this.answerList.length > 0) {
          this.idx = this.answerList[this.current - 1].pick;
        }
      } else {
        this.showTips("请先登录！", 1500);
        const _this = this;
        const timer2 = setTimeout(function () {
          _this.$router.push("/disc");
        }, 1600);
        _this.$once("hook:beforeDestroy", () => {
          clearTimeout(timer2);
        });
      }
    }
    this.throttlePick = throttle(this.handlePick, 1000, true);
  },
  computed: {
    answerList() {
      return JSON.parse(sessionStorage.getItem("answerList")) || [];
    },
    userInfo() {
      return JSON.parse(sessionStorage.getItem("userInfo"));
    },
    formatTitle() {
      return (data) => {
        if (data.includes("：")) {
          return data.match(/、(\S*)：/)[1];
        } else if (data.includes("忠心")) {
          return "忠心";
        } else if (data.includes(":")) {
          if (data.includes("、 ")) {
            return data.match(/、 (\S*):/)[1];
          } else {
            return data.match(/、(\S*):/)[1];
          }
        }
      };
    },
    formatDesc() {
      return (data) => {
        if (data.includes("：")) {
          return data.match(/：(\S*)/)[1];
        } else if (data.includes("忠心")) {
          return data.match(/心(\S*)/)[1];
        } else if (data.includes(":")) {
          return data.match(/:(\S*)/)[1];
        }
      };
    },
    total() {
      return this.question.length;
    },
  },
  methods: {
    getList() {
      getAnswerList({
        user_id: this.userInfo.user_id,
        test_paper_id: this.userInfo.test_paper_id,
      })
        .then((res) => {
          if (+res.code === 200) {
            this.question = res.data;
          } else {
            this.showTips(res.status_desc, 1500);
            const timer1 = setTimeout(() => {
              this.$router.push("/disc");
            }, 1600);
            this.$once("hook:beforeDestroy", () => {
              clearTimeout(timer1);
            });
          }
        })
        .catch((err) => {
          this.showTips(err, 1500);
          const timer2 = setTimeout(() => {
            this.$router.push("/disc");
          }, 1600);
          this.$once("hook:beforeDestroy", () => {
            clearTimeout(timer2);
          });
        });
    },
    goBack() {
      history.pushState(null, null, document.URL);
    },
    backMini() {
      if (this.from == "miniprogram") {
        console.log("miniprogram 返回小程序");
        wx.miniProgram.redirectTo({
          url: "/pagesSub/userCenter/careerPath/index",
        });
      } else if (this.from == "careerPathResult") {
        console.log("careerPathResult 返回小程序");

        wx.miniProgram.navigateBack();
      }
    },
    handleChange(type, isPick) {
      if (type === "prev") {
        this.transitionName = "";
        if (this.current === 1) {
          return false;
        }
        this.current = this.current - 1;
        this.idx = this.answerList[this.current - 1].pick;
        this.canSubmit = false;
        if (this.answerList.length === this.total) {
          this.canSubmit = true;
        }
      } else {
        if (isPick) {
          this.transitionName = "slide-left";
          if (!this.answerList[this.current - 1]) {
            // 未选择选项 不允许进入下一题
            this.showTips("请先选择！");
            return false;
          }
          if (this.current === this.total) {
            this.idx = this.answerList[this.current - 1].pick;
            return false;
          }
          this.idx = this.answerList[this.current - 1]
            ? this.answerList[this.current - 1].pick
            : "";
          this.picking = true;
          const timerPick = setTimeout(() => {
            this.current = this.current + 1;
            this.picking = false;
            this.idx = this.answerList[this.current - 1]
              ? this.answerList[this.current - 1].pick
              : "";
          }, 600);
          this.$once("hook:beforeDestroy", () => {
            clearTimeout(timerPick);
          });
          if (this.answerList.length === this.total) {
            this.canSubmit = true;
          }
        } else {
          this.transitionName = "";
          if (!this.answerList[this.current - 1]) {
            // 未选择选项 不允许进入下一题
            this.showTips("请先选择！");
            return false;
          }
          if (this.current === this.total) {
            this.idx = this.answerList[this.current - 1].pick;
            return false;
          }
          this.current = this.current + 1;
          this.idx = this.answerList[this.current - 1]
            ? this.answerList[this.current - 1].pick
            : "";
          if (this.answerList.length === this.total) {
            this.canSubmit = true;
          }
        }
      }
    },
    handlePick(item, index) {
      if (this.answerList && this.answerList[this.current - 1]) {
        // 已选择
        this.answerList.splice(this.current - 1, 1, {
          test_questions_id: item.test_questions_id,
          answer: item.disc,
          pick: item.title_options_id,
        });
      } else {
        // 未选择
        this.answerList.push({
          test_questions_id: item.test_questions_id,
          answer: item.disc,
          pick: item.title_options_id,
        });
      }
      sessionStorage.setItem("answerList", JSON.stringify(this.answerList));
      this.handleChange("next", true);
      if (this.current === this.total && this.answerList[this.current - 1]) {
        this.canSubmit = true;
      }
    },
    handleSubmit() {
      if (this.from === "miniprogram") {
        Dialog.confirm({
          title: "提示",
          message: "该功能在服务期内仅可使用一次，请确认后提交！",
        })
          .then(() => {
            this.submitting = true;
            let answerAll = [];
            this.answerList.forEach((item) => {
              answerAll.push({
                answer: item.answer,
                test_questions_id: item.test_questions_id,
              });
            });
            let params = {
              user_id: this.userInfo.user_id,
              test_paper_id: this.userInfo.test_paper_id,
              answerAll,
            };
            addAnswer(params)
              .then((res) => {
                this.submitting = false;
                if (+res.code === 200) {
                  this.$router.push(
                    "/disc/result?currentPersonId=" +
                      this.currentPersonId +
                      "&currentId=" +
                      this.currentId +
                      "&from=" +
                      this.from
                  );
                  sessionStorage.removeItem("userInfo");
                  sessionStorage.removeItem("answerList");
                } else {
                  this.showTips(res.status_desc);
                }
              })
              .catch((err) => {
                this.submitting = false;
                this.showTips(err);
              });
          })
          .catch(() => {
            // on cancel
          });
      }
    },
    showTips(msg, time) {
      if (document.querySelector(".dark-tips")) {
        document.querySelector(".dark-tips").remove();
      }
      var dom = document.createElement("span");
      dom.setAttribute("class", "dark-tips");
      document.body.appendChild(dom);
      var mytip = document.querySelector(".dark-tips");
      mytip.innerHTML = msg;
      const timer = setTimeout(
        function () {
          mytip.remove();
        },
        time ? time : 2000
      );
      this.$once("hook:beforeDestroy", () => {
        clearTimeout(timer);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
// @img: "../assets/images";

.question {
  height: 100vh;
  // background: url("@{img}/bg_question.png") no-repeat center / 100% 100%;

  .top {
    height: 32px;
    width: 100%;
  }

  &-wrap {
    margin: 0 16px;
    padding: 18px 18px 32px 18px;
    background-color: #fff;
    box-shadow: inset 0 1px 24px 0 #4e8ddf;
    border-radius: 8px;

    .title {
      font-size: 14px;
      color: #999;

      .num {
        font-size: 16px;
        letter-spacing: 2px;
      }
    }

    .tips {
      font-size: 16px;
      color: #333;
      margin: 20px 0 16px 0;
    }

    .question-list {
      min-height: 242px;
      list-style: none;
      overflow: hidden;

      &.disabled {
        pointer-events: none;
      }

      ul {
        position: relative;
        list-style: none;
        background-color: #fff;
        max-height: 242px;
        overflow: hidden;
      }

      .question-item {
        padding: 8px 12px;
        background: #f9f9f9;
        border-radius: 2px;
        margin-bottom: 8px;
        box-sizing: border-box;

        // transition:opacity 1s ease .8s;;
        // -moz-transition:opacity 1s  ease .8s;; /* Firefox 4 */
        // -webkit-transition:opacity 1s  ease .8s;; /* Safari and Chrome */
        // -o-transition:opacity 1s  ease .8s;; /* Opera */
        // &.pick {
        //   opacity: 0;
        // }
        .name {
          margin-bottom: 6px;
          font-size: 14px;
          color: #333;
        }

        .explan {
          font-size: 12px;
          color: #888;
        }

        &.active {
          background-color: #fff2ec;

          .name,
          .explan {
            color: #ff7638;
          }
        }
      }
    }

    .btn-bar {
      display: flex;
      justify-content: space-between;
      margin: 22px 28px 30px 28px;

      .btn {
        width: 50%;
        font-size: 16px;
        height: 36px;
        border-radius: 44px;
        color: #fff;
        background-color: #fff;

        &.next {
          margin-left: 18px;
          background-color: #4489f9;
        }

        &.prev {
          border: 2px solid #4489f9;
          color: #4489f9;
        }

        &.disabled.disabled {
          background-color: #dcdcdc;
          border-color: #dcdcdc;
          color: #fff;
          pointer-events: none;
        }
      }
    }

    .submit-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      width: 100%;
      height: 44px;
      box-shadow: 0 0 2px 0 #e1e1e1;
      border-radius: 4px;
      color: #fff;

      &.success {
        background-image: linear-gradient(-32deg, #2f72e5 0%, #328bef 100%);
      }

      &.disabled {
        background-color: #dcdcdc;
        background-image: none;
        pointer-events: none;
      }

      .loading {
        margin-right: 6px;

        img {
          width: 12px;
          height: 12px;
          vertical-align: inherit;
          animation: loading 1.5s linear infinite;
          transform-origin: center center;
        }
      }

      @keyframes loading {
        0% {
          transform: rotate(0);
          -ms-transform: rotate(0);
          /* IE 9 */
          -moz-transform: rotate(0);
          /* Firefox */
          -webkit-transform: rotate(0);
          /* Safari 和 Chrome */
          -o-transform: rotate(0);
        }

        100% {
          transform: rotate(180deg);
          -ms-transform: rotate(360deg);
          /* IE 9 */
          -moz-transform: rotate(360deg);
          /* Firefox */
          -webkit-transform: rotate(360deg);
          /* Safari 和 Chrome */
          -o-transform: rotate(360deg);
        }
      }
    }

    .info {
      margin-top: 8px;
      width: 102%;
      font-size: 12px;
      color: #bbb8b8;
      text-align: center;
    }
  }

  .slide-left-enter-active,
  .slide-left-leave-active,
  .slide-right-enter-active,
  .slide-right-leave-active {
    transition: all ease 0.4s;
  }

  .slide-left-enter,
  .slide-right-leave-to {
    opacity: 0;
    transform: translateX(50%);
  }

  .slide-left-leave-to,
  .slide-right-enter {
    opacity: 0;
    transform: translateX(-50%);
  }

  .slide-left-leave-active,
  .slide-right-leave-active {
    width: 100%;

    // .Loop(@index) when(@index<5) {
    //   &:nth-of-type(@{index}) {
    //     top: calc((@index - 1) * 59px);
    //   }

    //   .Loop(@index+1);
    // }

    // .Loop(0);
    $index: 0;
    @for $index from 1 through 5 {
      &:nth-of-type(#{$index}) {
        top: calc((#{$index} - 1) * 59px);
      }
    }
  }
  .download-app {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    left: 0;
    bottom: 0;
    padding: 12px 16px;
    width: 100%;
    color: #676e89;
    background: #ffffff;
    box-sizing: border-box;
    box-shadow: 0px -4px 12px 4px rgba(0, 0, 0, 0.06);
    z-index: 1000;

    .da-text {
      .text-desc {
        font-size: 14px;
        color: #222222;
      }

      .text-tips {
        margin-top: 8px;
        font-size: 12px;

        span {
          display: inline-block;
          margin-right: 4px;
          // color: #97a8a1;
        }
      }
    }

    .da-btn {
      width: 60px;
      height: 36px;
      font-size: 14px;
      border-radius: 8px;
      color: #ffffff;
      background: #ff7638;
      text-align: center;
      line-height: 36px;
    }
  }

  .back-btn {
    background-color: #ff7638;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #ffffff;
  }
}
</style>
